#include "OrgDao.h"
#include <QtSql/QSqlError>
#include <QJsonObject>
#include <QDebug>
#include <QSqlQuery>
#include  <QSqlRecord>
#include  <QStringList>
#include <QQueue>
#include <QHash>

OrgDao::OrgDao(QSqlDatabase& db) : db_(db) {}

QJsonArray OrgDao::getAllOrgList(QSqlDatabase& db)
{
    QJsonArray orgsArray;
    QSqlQuery query(db);

    // 使用高效的SQL查询并直接构建JSON
    if (!query.exec("SELECT ID, PARENT_ID, NAME, CODE FROM sys_org"))
    {
        qWarning() << "Query error:" << query.lastError().text();
        return orgsArray;
    }

    // 使用位置索引替代字段名（更快）
    const int idIdx = query.record().indexOf("ID");
    const int parentIdIdx = query.record().indexOf("PARENT_ID");
    const int nameIdx = query.record().indexOf("NAME");
    const int codeIdx = query.record().indexOf("CODE");

    while (query.next())
    {
        orgsArray.append(QJsonObject
        {
            {"id", query.value(idIdx).toString()},
            {"parentId", query.value(parentIdIdx).toString()},
            {"name", query.value(nameIdx).toString()},
            {"code", query.value(codeIdx).toString()}
        });
    }
    return orgsArray;
}

QJsonObject OrgDao::getOrgPage(QSqlDatabase& db, QJsonObject sysOrgPageParam)
{
    QJsonObject result;

    // 1. 解析分页参数
    int current = sysOrgPageParam.value("current").toInt(1);  // 默认第1页
    int size = sysOrgPageParam.value("size").toInt(10);       // 默认每页10条
    QString parentId = sysOrgPageParam.value("parentId").toString("");
    QString searchKey = sysOrgPageParam.value("searchKey").toString("");

    // 计算分页偏移量
    int offset = (current - 1) * size;

    // 2. 构建基础SQL条件
    QString baseSql = "FROM sys_org WHERE 1=1 ";
    QVariantList params;

    // 添加父ID条件
    if (!parentId.isEmpty())
    {
        baseSql += "AND PARENT_ID = ? ";
        params << parentId;
    }

    // 添加名称搜索条件
    if (!searchKey.isEmpty())
    {
        baseSql += "AND NAME LIKE ? ";
        params << "%" + searchKey + "%";
    }

    // 3. 查询总记录数
    int total = 0;
    QString countSql = "SELECT COUNT(*) " + baseSql;
    QSqlQuery countQuery(db);
    countQuery.prepare(countSql);

    for (int i = 0; i < params.size(); ++i)
    {
        countQuery.bindValue(i, params[i]);
    }

    if (countQuery.exec() && countQuery.next())
    {
        total = countQuery.value(0).toInt();
    }
    else
    {
        qWarning() << "Count query failed:" << countQuery.lastError().text();
    }

    // 4. 查询当前页数据
    QJsonArray records;
    QString dataSql = "SELECT ID, PARENT_ID, NAME, CATEGORY, SORT_CODE "
                      + baseSql +
                      "ORDER BY SORT_CODE ASC "
                      "LIMIT ? OFFSET ?";

    // 注意：这里需要复制params，因为要添加LIMIT和OFFSET参数
    QVariantList dataParams = params;
    dataParams << size << offset;

    QSqlQuery dataQuery(db);
    dataQuery.prepare(dataSql);

    for (int i = 0; i < dataParams.size(); ++i)
    {
        dataQuery.bindValue(i, dataParams[i]);
    }

    if (dataQuery.exec())
    {
        while (dataQuery.next())
        {
            QJsonObject record;
            record["id"] = dataQuery.value("ID").toString();
            record["_key"] = dataQuery.value("ID").toString();
            record["parentId"] = dataQuery.value("PARENT_ID").toString();
            record["name"] = dataQuery.value("NAME").toString();
            record["category"] = dataQuery.value("CATEGORY").toString();
            record["sortCode"] = dataQuery.value("SORT_CODE").toInt();

            records.append(record);
        }
    }
    else
    {
        qWarning() << "Data query failed:" << dataQuery.lastError().text();
        qWarning() << "SQL:" << dataQuery.lastQuery();
    }

    // 5. 构建返回结果
    result["total"] = total;
    result["size"] = size;
    result["current"] = current;
    result["records"] = records;

    // 计算总页数（可选）
    int pages = (total + size - 1) / size; // 向上取整
    result["pages"] = pages;

    return result;

}

int OrgDao::removeByIds(QSqlDatabase& db, QJsonArray sysOrgIdParamList)
{
    if (sysOrgIdParamList.isEmpty()) return 0;

    QStringList idList;
    for (const auto & id : sysOrgIdParamList)
    {
        idList << id.toString();
    }

    QSqlQuery query(db);
    int totalDeleted = 0;

    // 分批次处理
    const int BATCH_SIZE = 500;
    for (int i = 0; i < idList.size(); i += BATCH_SIZE)
    {
        auto batch = idList.mid(i, qMin(BATCH_SIZE, idList.size() - i));

        QStringList placeholders;
        placeholders.reserve(batch.size());
        for (int j = 0; j < batch.size(); j++)
        {
            placeholders.append("?");
        }

        QString sql = "DELETE FROM sys_org WHERE ID IN (";
        sql += placeholders.join(",") + ")";
        query.prepare(sql);
        for (const QString & id : qAsConst(batch))
        {
            query.addBindValue(id);
        }
        if (!query.exec())
        {
            qWarning() << "Delete error:" << query.lastError().text();
            db.rollback();
            return -1;
        }

        totalDeleted += query.numRowsAffected();
    }

    return totalDeleted;
}

QStringList OrgDao::getAllDescendantIds(QSqlDatabase& db, const QString& parentId)
{
    // 获取所有组织数据
    QSqlQuery query(db);
    if (!query.exec("SELECT ID, PARENT_ID FROM sys_org"))
    {
        qWarning() << "Query error:" << query.lastError().text();
        return QStringList();
    }

    // 构建父子关系映射
    QHash<QString, QStringList> childMap;
    while (query.next())
    {
        QString id = query.value("ID").toString();
        QString parentId = query.value("PARENT_ID").toString();
        childMap[parentId].append(id);
    }

    // 如果父节点不存在，直接返回空列表
    if (!childMap.contains(parentId) && parentId != "0")
    {
        qWarning() << "Parent ID not found:" << parentId;
        return QStringList();
    }

    // 使用BFS获取所有后代
    QStringList descendants;
    QQueue<QString> queue;

    // 添加初始节点的直接子节点
    if (childMap.contains(parentId))
    {
        for (const QString & child : qAsConst(childMap[parentId]))
        {
            queue.enqueue(child);
        }
    }

    // 遍历所有后代
    while (!queue.isEmpty())
    {
        QString current = queue.dequeue();
        descendants.append(current);

        // 添加当前节点的子节点
        if (childMap.contains(current))
        {
            for (const QString & child : qAsConst(childMap[current]))
            {
                queue.enqueue(child);
            }
        }
    }

    return descendants;
}
